<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    append-to-body
    :modal="false"
    top="74px"
    class="container-dailog transition-box"
    :class="$store.state.app.sidebar.opened ? 'openSidebar' : 'hideSidebar'"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="140px">
      <template>
        <el-form-item label="网关名称" prop="gatewayName">
          <el-input v-model="form.gatewayName" placeholder="请输入网关名称" />
        </el-form-item>
        <el-form-item label="所属组织" prop="deptId">
          <treeselect
            v-model="form.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择组织"
          />
        </el-form-item>
        <el-form-item label="SN" prop="sn">
          <el-input v-model="form.sn" placeholder="请输入sn编码" />
        </el-form-item>
        <el-form-item label="IMEI/NID码" prop="imei">
          <el-input v-model="form.imei" placeholder="请输入IMEI/NID码" />
        </el-form-item>
        <el-form-item label="网关型号" prop="gatewayModel">
          <el-input v-model="form.gatewayModel" placeholder="请输入网关型号" />
        </el-form-item>
        <el-form-item label="固件版本" prop="firmwareVersion">
          <el-input
            v-model="form.firmwareVersion"
            placeholder="请输入固件版本"
          />
        </el-form-item>
        <el-form-item label="卡号" prop="iccid">
          <el-input v-model="form.iccid" placeholder="请输入卡号" />
        </el-form-item>
        <el-form-item label="定位方式">
          <el-radio-group v-model="form.locationType">
            <el-radio
              v-for="dict in dict.type.location_type"
              :key="dict.value"
              :label="dict.raw.dictCode"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="网关地址">
          {{ form.addr
          }}<el-button type="primary" plain @click="openMapHandle"
            >地图</el-button
          >
        </el-form-item>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>

    <!-- 地图弹窗 -->
    <el-dialog
      :visible.sync="mapObj.show"
      width="40%"
      top="20px"
      title="地图"
      append-to-body
    >
      <div class="map">
        <el-autocomplete
          v-model.trim="mapObj.search"
          :fetch-suggestions="mapQuerySearch"
          placeholder="请输入详细地址"
          style="width: 100%"
          :trigger-on-focus="false"
          @select="handleSelect"
          class="map-autocomplete"
        />
        <baidu-map
          class="map-container"
          :zoom="15"
          :center="mapObj.cneter"
          inertial-dragging
          @click="paintPolyline"
          :scroll-wheel-zoom="true"
          @ready="handlerBMap"
        >
          <bm-marker :position="mapObj.marker" :dragging="false"> </bm-marker>
        </baidu-map>
        <el-form label-position="top" class="padding-20 bg-gray">
          <el-form-item label="详细地址" prop="addr">
            <el-input v-model="mapObj.addr" type="text" />
          </el-form-item>
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item label="经度" prop="lng">
                <el-input
                  :disabled="mapObj.disabled"
                  v-model="mapObj.lng"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="纬度" prop="lat">
                <el-input
                  :disabled="mapObj.disabled"
                  v-model="mapObj.lat"
                  type="text"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="操作">
                <el-button
                  v-if="mapObj.disabled"
                  @click="editLngLatHandle"
                  type="primary"
                  icon="el-icon-edit"
                  circle
                ></el-button>
                <template v-else>
                  <el-button @click="cancelLngLatHandel">取消</el-button>
                  <el-button @click="saveLngLatHandel" type="primary"
                    >保存</el-button
                  >
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="mapSubmitForm">确 定</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import { addGateway, updateGateway } from "@/api/iot/gateway";
import { getLocation } from "@/utils/map.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { BaiduMap, BmMarker } from "vue-baidu-map";

export default {
  name: "gateway-form-dialog",
  dicts: ["location_type"],
  components: { Treeselect, BaiduMap, BmMarker },
  props: {
    supThis: {
      type: Object,
      default: null,
    },
    deptOptions: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        gatewayName: [
          { required: true, message: "网关名称不能为空", trigger: "blur" },
        ],
        deptId: [
          { required: true, message: "所属组织id不能为空", trigger: "blur" },
        ],
        sn: [
          { required: true, message: "sn不能为空", trigger: "blur" },
        ],
        
      },
      // 地图参数
      mapObj: {
        show: false,
        addr: null,
        lng: null,
        lat: null,
        cneter: null,
        disabled: true,
        marker: null,
        defaultLocation: [],
        search: null,
      },
      BMap: null,
      map: null,
    };
  },
  methods: {
    async handlerBMap({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
    },
    handleSelect(item) {
      this.makerCenter(item.point)
      this.mapObj.addr = item.value;
      this.mapObj.lng = item.point.lng;
      this.mapObj.lat = item.point.lat;
      this.mapObj.search = ''
    },
    mapQuerySearch(queryString, cb) {
      var that = this;
      var myGeo = new this.BMap.Geocoder();
      myGeo.getPoint(
        queryString,
        function(point) {
          if (point) {
            that.coordinate = point;
            that.makerCenter(point);
          } else {
            that.coordinate = null;
          }
        },
        this.locationCity
      );
      var options = {
        onSearchComplete: function(results) {
          if (local.getStatus() === 0) {
            // 判断状态是否正确
            var s = [];
            for (var i = 0; i < results.getCurrentNumPois(); i++) {
              var x = results.getPoi(i);
              var item = { value: x.address + x.title, point: x.point };
              s.push(item);
              cb(s);
            }
          } else {
            cb();
          }
        },
      };
      var local = new this.BMap.LocalSearch(this.map, options);
      local.search(queryString);
    },
    makerCenter(point) {
      if (this.map) {
        this.map.clearOverlays();
        this.map.addOverlay(new this.BMap.Marker(point));
        this.mapObj.lng = point.lng;
        this.mapObj.lat = point.lat;
        this.mapObj.cneter= { lng: point.lng, lat: point.lat }
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gatewayName: null,
        deptId: null,
        sn: null,
        imei: null,
        gatewayStatus: null,
        gatewayModel: null,
        firmwareVersion: null,
        iccid: null,
        locationType: null,
        addr: null,
        lng: null,
        lat: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
      this.getLocation();
    },
    // 获取当前设备定位
    getLocation() {
      getLocation().then((res) => {
        this.form.addr = res.address;
        this.form.lng = res.lng;
        this.form.lat = res.lat;
      });
    },
    // 打开地图dialog
    openMapHandle() {
      this.mapObj.show = true;
      this.mapObj.addr = this.form.addr;
      this.mapObj.lng = this.form.lng;
      this.mapObj.lat = this.form.lat;
      const point = new BMap.Point(this.mapObj.lng, this.mapObj.lat);
      this.mapObj.marker = point;
      this.mapObj.cneter = point;
    },
    // 点击地图
    paintPolyline(e) {
      const point = e.point;
      this.inverseLocation(point).then((address) => {
        this.mapObj.addr = address;
        this.mapObj.lng = point.lng;
        this.mapObj.lat = point.lat;
        this.mapObj.marker = point;
        this.mapObj.cneter = point;
      });
    },
    // 点击修改地图经纬度
    editLngLatHandle() {
      this.mapObj.disabled = false;
      this.mapObj.defaultLocation = [this.mapObj.lng, this.mapObj.lat];
    },
    // 取消修改经纬度
    cancelLngLatHandel() {
      this.mapObj.disabled = true;
      this.mapObj.lng = this.mapObj.defaultLocation[0];
      this.mapObj.lat = this.mapObj.defaultLocation[1];
      this.mapObj.defaultLocation = [];
    },
    // 经纬度逆解析地址
    inverseLocation(point) {
      return new Promise((resolve, reject) => {
        const geoc = new BMap.Geocoder();
        geoc.getLocation(point, (res) => {
          resolve(res.address);
        });
      });
    },
    // 保存修改的经纬度
    saveLngLatHandel() {
      const _this = this;
      if (this.mapObj.lng && this.mapObj.lat) {
        const geoc = new BMap.Geocoder();
        const point = new BMap.Point(this.mapObj.lng, this.mapObj.lat);
        this.inverseLocation(point).then((address) => {
          _this.mapObj.addr = address;
          _this.mapObj.marker = point;
          _this.mapObj.cneter = point;
          _this.mapObj.disabled = true;
          _this.mapObj.defaultLocation = [];
        });
      } else {
        this.$modal.msgError("请选择地图位置");
      }
    },
    // 地图提交
    mapSubmitForm() {
      if (this.mapObj.addr && this.mapObj.lng && this.mapObj.lat) {
        this.form.addr = this.mapObj.addr;
        this.form.lng = this.mapObj.lng;
        this.form.lat = this.mapObj.lat;
        this.mapObj.show = false;
      } else {
        this.$modal.msgError("请选择地图位置");
      }
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateGateway(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.supThis.getList();
            });
          } else {
            addGateway(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.supThis.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
  },
};
</script>

<style lang="scss" scoped>
.map-container {
  width: 100%;
  height: 400px;
}
.map {
  position: relative;
}
.map-autocomplete {
  position: absolute;
  width: 350px !important;
  right: 20px;
  top: 20px;
  z-index: 9;
}
</style>
